import requests
import os


def download_m3u8_video(url, file_path):
    r = requests.get(url)
    if r.status_code != 200:
        print("m3u8视频下载链接无效")
        return False

    m3u8_list = r.text.split("\n")
    m3u8_list = [i for i in m3u8_list if i and i[0] != "#"]

    ts_list = []
    for ts_url in m3u8_list:
        ts_url = url.rsplit("/", 1)[0] + "/" + ts_url
        ts_list.append(ts_url)

    with open(file_path, "wb") as f:
        for ts_url in ts_list:
            r = requests.get(ts_url)
            if r.status_code == 200:
                f.write(r.content)
    print("m3u8视频下载完成")
    return True


def convert_ts_to_mp4(ts_file_path, mp4_file_path):
    os.system(f"C:/ffmpeg/bin/ffmpeg.exe -i {ts_file_path} -c copy {mp4_file_path}")


def convert_mp4_to_wav():
    os.system(
        f"C:/ffmpeg/bin/ffmpeg.exe -i mp4/video.mp4 -vn -acodec pcm_s16le -ar 44100 -ac 2 mp4/output.wav"
    )


if __name__ == "__main__":
    url = "https://flv3.bn.netease.com/d62110b9785041a97d525f1f11142222321e088678afbfb96e467bec880a68ad0f4894da332a2632f7229e16e0de3658e95973dff294c5bc2dedaf9fd83b2a59d91609b8eab65fda6bdd73bd0a476bfa06c973eee6490e2a979a7ba27d2c4b1240f7f670f8bc504456630c04d4f0c4889f495dacf55b8863.m3u8"
    ts_file_path = "ts/ts"
    mp4_file_path = "mp4/video.mp4"

    download_m3u8_video(url, ts_file_path)
    convert_ts_to_mp4(ts_file_path, mp4_file_path)
